package org.neptune.service.shiro;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.neptune.api.entity.SeckillUser;
import org.neptune.service.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author lwl
 * @date 2019/8/15 11:28
 */
public class CustomRealm extends AuthorizingRealm {

	private static final Logger LOGGER = LoggerFactory.getLogger(CustomRealm.class);

	@Autowired
	private UserService userService;
	// @Autowired
	// private RoleService roleService;
	// @Autowired
	// private PermService permService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (principals == null){
			throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
		}

		SeckillUser user = (SeckillUser) getAvailablePrincipal(principals);

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		LOGGER.info("获取角色信息：" + user.getRoles());
		// System.out.println("获取权限信息："+user.getPerms());
		info.setRoles(user.getRoles());
		// info.setStringPermissions(user.getPerms());
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {

		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();

		if (username == null){
			throw new AccountException("Null usernames are not allowed by this realm.");
		}

		SeckillUser seckillUser = userService.queryUserByUserName(username);

		if (seckillUser == null){
			throw new UnknownAccountException("No account found for admin [" + username + "]");
		}

		// 查询用户的角色和权限存到SimpleAuthenticationInfo中，这样在其它地方
		// SecurityUtils.getSubject().getPrincipal()就能拿出用户的所有信息，包括角色和权限
		// Set<String> roles = roleService.getRolesByUserId(userDB.getUid());
		// Set<String> perms = permService.getPermsByUserId(userDB.getUid());
		// userDB.getRoles().addAll(roles);
		// userDB.getPerms().addAll(perms);

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(seckillUser,
				seckillUser.getPassword(), getName());

		return info;

	}
}
